// CustomTable.js
import { Node } from '@tiptap/core'
import { VueNodeViewRenderer } from '@tiptap/vue-3'
import TableComponent from './TableComponent.vue'

export default Node.create({
  name: 'customTable',

  group: 'block',

  content: 'block*', // 允许表格后跟随其他内容

  addOptions() {
    return {
      HTMLAttributes: {},
      defaultData: [{ date: '', name: '', address: '' }]
    }
  },

  addAttributes() {
    return {
      data: {
        default: this.options.defaultData
      },
      editable: {
        default: true
      }
    }
  },

  parseHTML() {
    return [
      {
        tag: 'div[data-custom-table]'
      }
    ]
  },

  renderHTML({ HTMLAttributes }) {
    return ['div', { ...HTMLAttributes, 'data-custom-table': '' }, 0]
  },

  addNodeView() {
    return VueNodeViewRenderer(TableComponent)
  },

  addCommands() {
    return {
      insertCustomTable:
        (options = {}) =>
        ({ chain }) => {
          return chain()
            .insertContent({
              type: this.name,
              attrs: options,
              content: [
                {
                  type: 'paragraph', // 自动添加空段落实现换行
                  content: [
                    {
                      type: 'text',
                      text: ' '
                    }
                  ]
                }
              ]
            })
            .focus()
            .run()
        }
    }
  }
})
